package tau.dimes.visualization.applet;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

import processing.core.PApplet;

/**
 * Implements the mechanism for requesting data over HTTP.
 */
class HttpRequest
{
	private final PApplet applet;

	/**
	 * Constructs a new HttpRequest.
	 * @param applet A reference to the containing applet.
	 */
	HttpRequest(PApplet applet)
	{
		this.applet = applet;
	}

	/**
	 * Send the request (from parameter) and return the response.
	 * @return Response from HTTP request.
	 */
	String sendRequest()
	{
		try
		{
			// Construct data
			String data = URLEncoder.encode("xmlrequest", "UTF-8") + "="
				+ URLEncoder.encode(Parameters.getXmlrequest(), "UTF-8");

			// Send data
			URL url = new URL(applet.getCodeBase(), "VisualizationServlet");
			URLConnection conn = url.openConnection();
			conn.setDoOutput(true);
			OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
			wr.write(data);
			wr.flush();

			// Get the response
			BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			String line;
			String result = "";
			while ((line = rd.readLine()) != null)
			{
				result += line;
			}

			rd.close();
			return result;
		}
		catch (Exception e)
		{
			return null;
		}
	}
}